package io.github.leon406.view.textview

import android.content.Context
import android.content.res.ColorStateList
import android.graphics.Color
import android.text.SpannableStringBuilder
import android.util.AttributeSet
import io.github.leon406.view.span.LinkTouchMovementMethod
import io.github.leon406.view.span.OnSpanClickListener
import io.github.leon406.view.span.QMUILinkify
import me.leon.ui.R

/** url/ e-mail / phone */
class LinkTextView
@JvmOverloads
constructor(context: Context, attributes: AttributeSet? = null, defaultStyle: Int = 0) :
    SpanTouchTextView(context, attributes, defaultStyle), OnSpanClickListener {

    /** 链接文字颜色 */
    private var mLinkTextColor: ColorStateList? = null

    /** 链接背景颜色 */
    private var mLinkBgColor: ColorStateList? = null
    private var mOriginText: CharSequence? = null
    private var mAutoLinkMaskCompat = 0

    private var linkSpanClickListener: LinkSpanClickListener? = null

    fun addLinkSpanListener(listener: LinkSpanClickListener?) {
        linkSpanClickListener = listener
    }

    init {
        mAutoLinkMaskCompat = autoLinkMask or AUTO_LINK_MASK_REQUIRED
        highlightColor = Color.TRANSPARENT
        movementMethod = LinkTouchMovementMethod.instance

        context
            .obtainStyledAttributes(attributes, R.styleable.LinkTextView)
            .apply {
                mLinkBgColor =
                    getColorStateList(R.styleable.LinkTextView_link_text_background_color)
                mLinkTextColor = getColorStateList(R.styleable.LinkTextView_link_text_color)
                mOriginText?.let { text = mOriginText }
            }
            .recycle()
    }

    override fun setText(text: CharSequence?, type: BufferType?) {
        mOriginText = text
        var tmpText = text
        if (!text.isNullOrEmpty()) {
            SpannableStringBuilder(text).run {
                QMUILinkify.addLinks(
                    this,
                    mAutoLinkMaskCompat,
                    mLinkTextColor,
                    mLinkBgColor,
                    this@LinkTextView
                )
                tmpText = this
            }
        }
        super.setText(tmpText, type)
    }

    companion object {
        const val TAG = "LinkTextView"
        var AUTO_LINK_MASK_REQUIRED =
            QMUILinkify.PHONE_NUMBERS or QMUILinkify.EMAIL_ADDRESSES or QMUILinkify.WEB_URLS
    }

    override fun onSpanClick(text: String?): Boolean {
        return linkSpanClickListener?.let {
            it.onLinkClick(text)
            true
        }
            ?: false
    }
}

fun interface LinkSpanClickListener {
    fun onLinkClick(text: String?)
}
